package com.qlm.controller;

import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.qlm.service.impl.GiftServiceImpl;

public class UserController extends Controller{

	public void queryByNickName(){
		String nickName = getPara("name");
		List<Record> find = Db.find("select * from t_user where nick_name like '%"+nickName+"%'");
		renderJson(find);
	}
	
	public void add(){
		String openid = getPara("openid");
		String giftid = getPara("giftid");
		String num = getPara("num");
		Record result = new Record();
		Record user = Db.findFirst("select * from t_user where openid = ?",openid);
		Record findFirst = Db.findFirst("select * from t_gift where id = ?",giftid);
		if(findFirst == null || user == null){
			result.set("status", false);
		}else{
			Record r = Db.findFirst("select * from t_daili where openid_ = ? and gift_id_ = ?",openid,giftid);
			if(r != null){
				result.set("status", false);
				result.set("msg","已经存在该优惠了");
			}else{
				String nickName = user.getStr("nick_name");
				String head_pic = user.getStr("head_pic");
				String name = findFirst.getStr("name_");
				Db.update("insert into t_daili (openid_,gift_id_,num_,gift_name_,head_pic,nick_name,create_time_) values(?,?,?,?,?,?,now())",openid,giftid,num,name,head_pic,nickName);
				GiftServiceImpl.callCache("cache/updateDaili");
				result.set("status", true);
			}
			
		}
		renderJson(result);
	}
	
	public void daili(){
		List<Record> find = Db.find("select * from t_daili order by create_time_ desc");
		List<Record> gift = Db.find("select * from t_gift where online_ = 1");
		setAttr("gifts", gift);
		setAttr("list", JsonKit.toJson(find));
		render("/page/daili.jsp");
	}
	
	public void del(){
		String id =getPara("id");
		Db.update("delete from t_daili where id = ?",id);
		GiftServiceImpl.callCache("cache/updateDaili");
		renderJson(new Record());
	}
}
